import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
def f(x):
return (x-1) * (x-2) * (x-3) * (x-5)
def df(x):
return 4*x*x*x - 33*x*x + 82*x -61
def gd(x0, nu, niter=None, epsilon=None):
xpred = x0
xcurrent = xpred - nu*df(xpred)
xlist = [xcurrent]
if niter:
i = 1
while i <= niter and df(xcurrent) != 0:
xpred = xcurrent
xcurrent = xcurrent - nu*df(xcurrent)
xlist.append(xcurrent)
i += 1
if epsilon:
while np.abs(xcurrent - xpred) > epsilon and df(xcurrent) != 0:
xpred = xcurrent
xcurrent = xcurrent - nu*df(xcurrent)
xlist.append(xcurrent)
return xlist, xcurrent, i
x0 = 5
nu = 0.001
xlist,argmin, nb = gd(x0, nu, 443)
print(argmin)
import time
x = np.linspace(0., 6, 100)
plt.plot(x, f(x), 'r--')
for i in range(len(xlist)):
plt.plot(xlist[i], f(xlist[i]), 'bo')
#time.sleep(1)
plt.show()
x0 = 5
nu = 0.01
xlist,argmin, nb = gd(x0, nu, 39)
import time
x = np.linspace(0., 6, 100)
plt.plot(x, f(x), 'r--')
for i in range(len(xlist)):
plt.plot(xlist[i], f(xlist[i]), 'bo')
#time.sleep(1)
plt.show()
print('xmin: ',argmin, 'nb iterations: ',nb)